<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from "vue";
import { storeToRefs } from "pinia";
import { useTradeStore } from "@/store/modules/tradeStore";

import type { TradeEnabledAppInfo } from "@/types/trade.types";
import type { LogSchema, RiskReportSchema } from "@/types/account.types";
import { useTradeLogsTable, useRiskReportsTable } from "./TradeTabs";
import { useBreakpointQuery } from "@/utils/device";
import TradePositionTable from "./components/TradePositionTable.vue";
import TradePositionAnalysisTable from "./components/TradePositionAnalysisTable.vue";
import Order from "@/components/tables/account/Order.vue";
import Trade from "@/components/tables/account/Trade.vue";
import ActiveOrder from "@/components/tables/account/ActiveOrder.vue";

defineOptions({
  name: "trade-tabs"
});

const props = defineProps<{
  selectedApp: TradeEnabledAppInfo | null;
}>();

const tableContainerRef = ref<HTMLElement | null>(null);
const tableHeight = ref<string | null>();

const updateTableHeight = () => {
  if (tableContainerRef.value) {
    tableHeight.value = `${tableContainerRef.value.clientHeight}px`;
  }
};

onMounted(() => {
  updateTableHeight();
  window.addEventListener("resize", updateTableHeight);
});

onUnmounted(() => {
  window.removeEventListener("resize", updateTableHeight);
});

const tradeStore = useTradeStore();
const { activeTab, accountInfo } = storeToRefs(tradeStore);

const { isSmUp } = useBreakpointQuery();

// Extract data from accountInfo
const orders = computed(() =>
  accountInfo.value ? Array.from(accountInfo.value.orders.values()) : []
);

const trades = computed(() =>
  accountInfo.value ? Array.from(accountInfo.value.trades.values()) : []
);

const logs = computed<LogSchema[]>(() => {
  return accountInfo.value?.logs ?? [];
});

const riskReports = computed<RiskReportSchema[]>(() => {
  return accountInfo.value
    ? Array.from(accountInfo.value.risk_reports.values())
    : [];
});

const tradeLogsTable = useTradeLogsTable();
const logTableSize = tradeLogsTable.tableSize;
const logColumns = tradeLogsTable.logColumns;
const getRowClassName = tradeLogsTable.getRowClassName;

const riskReportsTable = useRiskReportsTable();
const riskReportsTableSize = riskReportsTable.tableSize;
const riskReportColumns = riskReportsTable.riskReportColumns;
</script>

<template>
  <div class="flex h-full flex-col">
    <el-tabs
      v-model="activeTab"
      class="flex h-full flex-col"
      type="border-card"
      size="small"
    >
      <!-- Always visible: Active Orders tab -->
      <el-tab-pane
        label="挂单"
        name="active_orders"
        lazy
        class="flex h-full flex-col"
      >
        <div ref="tableContainerRef" class="min-h-0 flex-1 overflow-hidden">
          <ActiveOrder
            :orders="orders"
            :height="tableHeight"
            size="small"
            compact
          />
        </div>
      </el-tab-pane>

      <!-- Mobile only: Position and PositionAnalysis tabs -->
      <el-tab-pane
        v-if="!isSmUp()"
        label="持仓"
        name="positions"
        lazy
        class="flex h-full flex-col"
      >
        <div ref="tableContainerRef" class="min-h-0 flex-1 overflow-hidden">
          <TradePositionTable :height="tableHeight" compact />
        </div>
      </el-tab-pane>

      <el-tab-pane
        v-if="!isSmUp()"
        label="持仓分析"
        name="position_analysis"
        lazy
        class="flex h-full flex-col"
      >
        <div ref="tableContainerRef" class="min-h-0 flex-1 overflow-hidden">
          <TradePositionAnalysisTable :height="tableHeight" compact />
        </div>
      </el-tab-pane>

      <!-- Always visible: Orders tab -->
      <el-tab-pane label="委托" name="orders" lazy class="flex h-full flex-col">
        <div ref="tableContainerRef" class="min-h-0 flex-1 overflow-hidden">
          <Order :orders="orders" :height="tableHeight" size="small" compact />
        </div>
      </el-tab-pane>

      <!-- Always visible: Trades tab -->
      <el-tab-pane label="成交" name="trades" lazy class="flex h-full flex-col">
        <div ref="tableContainerRef" class="min-h-0 flex-1 overflow-hidden">
          <Trade :trades="trades" :height="tableHeight" size="small" compact />
        </div>
      </el-tab-pane>

      <el-tab-pane
        label="风控"
        name="risk_reports"
        lazy
        class="flex h-full flex-col"
      >
        <div ref="tableContainerRef" class="min-h-0 flex-1 overflow-hidden">
          <pure-table
            :data="riskReports"
            :columns="riskReportColumns"
            :row-key="row => row.name"
            :size="riskReportsTableSize"
            :height="tableHeight"
          />
        </div>
      </el-tab-pane>

      <!-- Always visible: Logs tab -->
      <el-tab-pane label="日志" name="logs" lazy class="flex h-full flex-col">
        <div ref="tableContainerRef" class="min-h-0 flex-1 overflow-hidden">
          <pure-table
            :data="logs"
            :columns="logColumns"
            :row-key="row => `${row.time}-${row.source}-${row.level}`"
            :row-class-name="({ row }) => getRowClassName(row)"
            :size="logTableSize"
            :default-sort="{ prop: 'time', order: 'descending' }"
            :height="tableHeight"
          />
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style scoped>
:deep(.el-tabs__header) {
  --el-tabs-header-height: 32px;
}

:deep(.el-tabs--border-card > .el-tabs__content) {
  padding: 4px;
}
</style>
